import Bb from 'backbone';

const BaseCollection = Bb.Collection.extend({
    constructor: function (models, options) {
        options = options || {};
        if ('url' in options) {
            this.url = options.url;
        }
        Bb.Collection.apply(this, arguments);
    },
    fetch(options) {
        const xhr_request = Bb.Collection.prototype.fetch.call(
            this, options
        );
        options = options || {};
        if (xhr_request && !options.silent) {
            xhr_request.done(() => {
                this.trigger('fetched');
            })
        }
        return xhr_request
    },
    validate() {
        var result = {};
        this.each(
            function (model) {
                let func = model.validateModel;
                if (!func) {
                    func = model.validate;
                }
                if (func) {
                    Object.assign(result, func.bind(model)());
                } else {
                    console.error("Le modèle n'a pas de méthode validate");
                }
            }

        );
        return result;
    }
})
export default BaseCollection;